from apscheduler.schedulers.background import BackgroundScheduler
from flask_cors import CORS
import logging

from cfg import cfg
from cfg.exts import db
from cfg.model.UserModel import *
from cfg.model.BasicInfo import *
from flask_migrate import Migrate
from cfg.banner import star
from cfg.repo.json_flask import JsonFlask
from cfg.repo.json_response import JsonResponse
from cfg.repo.custom_error import CustomError
from cfg.token.middleware import token_validation_middleware, clear_token

# 自定义了Flask
app = JsonFlask(__name__)
# 设置允许跨域
CORS(app, origins='*', supports_credentials=True)
# 绑定配置文件
app.config.from_object(cfg)
# 初始化
db.init_app(app)
# 差异性合并sql
migrate = Migrate(app, db)
# 设置日志级别为 DEBUG
app.logger.setLevel(logging.ERROR)
# 注册中间件到 Flask 应用
app.before_request(token_validation_middleware)
app.teardown_request(clear_token)
# 一个后台调度器
scheduler = BackgroundScheduler()
scheduler.start()

# 统一异常返回
@app.errorhandler(Exception)
def error_handler(e):
    """
    全局异常捕获，也相当于一个视图函数
    """
    logging.error(f"{str(e)}")
    return JsonResponse.error(msg=f"{str(e)}", code=500)


@app.errorhandler(CustomError)
def error_custom_handler(e):
    """
    全局异常捕获，也相当于一个视图函数
    """
    logging.error(f"{str(e)}")
    return JsonResponse.error(msg=e.message, code=e.code)
